package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"news-hub/cache"
	"news-hub/model"
	"strconv"
	"time"
)

func DataList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var New []model.New
	redis_key := "list_page" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Debug().Find(&New)
		jsonData, _ := json.Marshal(New)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Minute*2)
	} else {
		json.Unmarshal([]byte(cacheData), &New)
	}
	var total int64
	model.DB.Model(&model.New{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  New,
		"total": total,
	})
	return
}

func DataDetail(c *gin.Context) {
	id := c.Query("id")
	var New model.New
	redis_key := "list_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id", id).First(&New)
		jsonData, _ := json.Marshal(New)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Minute*2)
	} else {
		json.Unmarshal([]byte(cacheData), &New)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": New,
	})
	return
}
